package com.google.code.opengw.support;

import java.io.PrintWriter;
import java.io.StringWriter;

import org.apache.log4j.Appender;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.DailyRollingFileAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;

import com.google.code.opengw.server.Server;

public class OpenGWLogger {
	private static Logger logger = Logger.getRootLogger();
	
	static{		
		try{
			logger.setLevel(Level.INFO);
			PatternLayout patternLayout = new PatternLayout();
			patternLayout.setConversionPattern("[#| %d{dd-MMM-yyyy HH:mm:ss.SSS Z} |%p| %m ]%n");
			Appender consoleAppender = new ConsoleAppender(patternLayout);
			consoleAppender.setName("consoleAppender");
			Appender fileAppender;
			fileAppender = new DailyRollingFileAppender(patternLayout, Server.LOG4J_LOG_PATH, "'.'yyyy-MM-dd-HH");
			fileAppender.setName("fileAppender");
			logger.addAppender(fileAppender);
			logger.addAppender(consoleAppender);
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(1);
		} 
	}

	
	public static void addInfo(Class clazz, String message){
		StringBuilder builder = new StringBuilder(clazz.getName())
			.append(" | ")
			.append(message);
		logger.info(builder.toString());
	}
	
	public static void addWarn(Class clazz, String message){
		StringBuilder builder = new StringBuilder(clazz.getName())
			.append(" | ")
			.append(message);
		logger.warn(builder.toString());
	}
	
	public static void addError(Class clazz, String message, Throwable th){
		StringWriter sw = new StringWriter();
        th.printStackTrace(new PrintWriter(sw));
		StringBuilder builder = new StringBuilder(clazz.getName())
			.append(" | ")
			.append(message)
			.append("|")
			.append(sw.toString());

		logger.error(builder.toString());
	}
	
}
